package org.file5.service.impl;

import org.apache.log4j.Logger;
import org.file5.dao.DaoFascade;
import org.file5.domain.BaseEntity;
import org.file5.domain.EntityIndex;
import org.file5.search.IdeaExchangeConstants;
import org.file5.service.EntityIndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import com.google.appengine.api.labs.taskqueue.TaskOptions;
import com.googlecode.objectify.Key;

@Service("entityIndexService")
public class EntityIndexServiceImpl implements EntityIndexService {

	private final Logger logger = Logger.getLogger(this.getClass());
	@Autowired
	DaoFascade df;

//	@Override
//	public <E extends BaseEntity> EntityIndex<E> createEntityIndex(
//			Class<E> entityClass, String uid) {
//		// TODO Auto-generated method stub
//		return null;
//	}

	@Override
	public <E extends BaseEntity> EntityIndex<E> findEntityIndex(
			Class<E> entityClass, String uid) {
		Key<E> key = new Key<E>(entityClass,uid);
		EntityIndex<E> ei = df.getEntityIndexDao().findByEntityKey(key);
		return ei;
	}

	@Override
	public <E extends BaseEntity> EntityIndex<E> findUnIndexedEntity() {
		 
		return df.getEntityIndexDao().findUnIndexedEntity( );
	}

	/**
	 * Add the task to a {@link Queue} to index entity.
	 * 
	 */
	@Override
	public <E extends BaseEntity> void addIndexTask(
			Class<E> entityClass, String uid) {
		/* Use Task Queue to queue the task to index. */
		Queue queue = QueueFactory.getQueue(IdeaExchangeConstants.INDEX_QUEUE);
		String url = IdeaExchangeConstants.INDEX_URL
				+ entityClass.getSimpleName() + "/" + uid+".htm";
		TaskOptions taskOptions = TaskOptions.Builder.url(url);

		queue.add(taskOptions);
	}

}
